package com.moyuxi.sound_of_the_forest.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.BitmapFactory
import android.media.MediaMetadataRetriever
import android.os.Binder
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.widget.RemoteViews
import android.widget.Toast
import androidx.core.app.NotificationCompat
import com.moyuxi.sound_of_the_forest.MainActivity
import com.moyuxi.sound_of_the_forest.MediaPlayerHelper
import com.moyuxi.sound_of_the_forest.R


class AudioService : Service() {
    private val CHANNEL_ID = 1
    private val CHANNEL_NAME = "LinMing"

    private lateinit var mediaPH: MediaPlayerHelper
    private lateinit var binder: AudioServiceBinder

    private var notificationManager: NotificationManager? = null
    private var notification: Notification? = null


    private val receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == NotificationConst.ACTION) {
                when (intent.getIntExtra(NotificationConst.STATE, -1)) {
                    NotificationConst.LAST -> mediaPH.playLastMusic()
                    NotificationConst.CURRENT -> mediaPH.playCurrentMusic()
                    NotificationConst.NEXT -> mediaPH.playNextMusic()
                    NotificationConst.CLOSE -> closeNotification()
                    -1 -> {}
                    else -> Toast.makeText(context, "系统出错，请稍后重试！", Toast.LENGTH_SHORT)
                        .show()
                }
//                updateNotification()
            }
        }
    }

    override fun onCreate() {
        super.onCreate()
        if (!::mediaPH.isInitialized) {
            mediaPH = MediaPlayerHelper.instance
        }
        if (!::binder.isInitialized) {
            binder = AudioServiceBinder()
        }

        val filter = IntentFilter(NotificationConst.ACTION)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
        } else {
            registerReceiver(receiver, filter)
        }

        notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "$CHANNEL_ID", CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT
            )
            channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
            notificationManager!!.createNotificationChannel(channel)
        }
        val views = RemoteViews(packageName, R.layout.notifiication_layout)
        setViewEvent(views)
        updateNotification(views)
        val notificationBuilder =
            NotificationCompat.Builder(this, "$CHANNEL_ID").setSmallIcon(R.drawable.logo)
                .setContentTitle("标题").setCustomBigContentView(views)
                .setContentIntent(getPendingIntent(this, -1)).setOngoing(true)
        notification = notificationBuilder.build()
//        notificationManager!!.notify(CHANNEL_ID, notification)
        startForeground(CHANNEL_ID, notification)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i("TAG", "onStartCommand: into")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent?): IBinder {
        return binder
    }

    override fun onUnbind(intent: Intent?): Boolean {
        binder.isRunningForeground = false
        closeNotification()
        unregisterReceiver(receiver)
        return super.onUnbind(intent)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i("TAG", "onDestroy: into")
//        closeNotification()
//        unregisterReceiver(receiver)
    }

    private fun closeNotification() {
        this.stopForeground(STOP_FOREGROUND_REMOVE)
        notificationManager?.cancel(CHANNEL_ID)
        mediaPH.stopMusic()
    }

    private fun setViewEvent(views: RemoteViews) {
        views.setOnClickPendingIntent(R.id.ib_last, getPendingIntent(this, NotificationConst.LAST))
        views.setOnClickPendingIntent(
            R.id.ib_current, getPendingIntent(this, NotificationConst.CURRENT)
        )
        views.setOnClickPendingIntent(R.id.ib_next, getPendingIntent(this, NotificationConst.NEXT))
        views.setOnClickPendingIntent(
            R.id.ib_close, getPendingIntent(this, NotificationConst.CLOSE)
        )
    }

    private fun updateNotification(views: RemoteViews) {
        mediaPH.playMusicBean.observeForever {
            views.setTextViewText(R.id.tv_name, it.name)
            views.setTextViewText(R.id.tv_singer, it.singer)
            val mmr = MediaMetadataRetriever()
            val bytes = if (it.path.isNotEmpty()) {
                mmr.setDataSource(it.path)
                mmr.embeddedPicture
            } else null
            if (bytes != null) {
                val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                views.setImageViewBitmap(R.id.imageView, bitmap)
            } else {
                views.setImageViewResource(R.id.imageView, R.drawable.icon_music)
            }
            if (notificationManager != null && notification != null && binder.isRunningForeground) {
                notificationManager!!.notify(CHANNEL_ID, notification)
            }
        }
        mediaPH.isPlaying.observeForever {
            if (!it) views.setImageViewResource(R.id.ib_current, R.drawable.icon_play)
            else views.setImageViewResource(R.id.ib_current, R.drawable.icon_pause)
            if (notificationManager != null && notification != null && binder.isRunningForeground) {
                notificationManager!!.notify(CHANNEL_ID, notification)
            }
        }
    }

    private fun getPendingIntent(context: Context, state: Int): PendingIntent {
        val bundle = Bundle()
        bundle.putInt(NotificationConst.STATE, state)
        val intent = Intent(NotificationConst.ACTION).putExtras(bundle)
        return when (state) {
            NotificationConst.LAST -> PendingIntent.getBroadcast(
                context, NotificationConst.LAST, intent, PendingIntent.FLAG_MUTABLE
            )

            NotificationConst.CURRENT -> PendingIntent.getBroadcast(
                context, NotificationConst.CURRENT, intent, PendingIntent.FLAG_MUTABLE
            )

            NotificationConst.NEXT -> PendingIntent.getBroadcast(
                context, NotificationConst.NEXT, intent, PendingIntent.FLAG_MUTABLE
            )

            NotificationConst.CLOSE -> PendingIntent.getBroadcast(
                context, NotificationConst.CLOSE, intent, PendingIntent.FLAG_MUTABLE
            )

            else -> PendingIntent.getActivity(
                context, -1, Intent(context, MainActivity::class.java), PendingIntent.FLAG_MUTABLE
            )
        }
    }

    inner class AudioServiceBinder : Binder() {
//        fun getAudioServiceBinder():AudioServiceBinder{
//            return this@AudioServiceBinder
//        }

        var isRunningForeground: Boolean = true

        fun getAudioService(): AudioService {
            return this@AudioService
        }

        fun getMediaPlayerHelper(): MediaPlayerHelper {
            return mediaPH
        }

        /**
         * 上一首
         */
        fun playLastMusic() {
            mediaPH.playLastMusic()
        }

        /**
         * 播放/暂停
         */
        fun playCurrentMusic() {
            mediaPH.playCurrentMusic()
        }

        /**
         * 下一首
         */
        fun playNextMusic() {
            mediaPH.playNextMusic()
        }

        /**
         * 结束音乐播放器
         */
        fun stopMusic() {
            mediaPH.stopMusic()
        }

    }
}